package cn.fl.capital.controller;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.condition.CapOvdErrLogQueryCondition;
import cn.fl.capital.dto.CapOvdErrLogDTO;
import cn.fl.capital.service.ICapOvdErrLogService;
import cn.fl.capital.vo.CapOvdErrLogVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;
import com.alibaba.fastjson.JSONObject;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 资方逾期异常记录表 控制层
 */
@Controller
@RequestMapping("/capital/capOvdErrLog")
public class CapOvdErrLogController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(CapOvdErrLogController.class);
	
	/**
	 * CapOvdErrLog 服务层BEAN
	 */
	@Autowired
	private ICapOvdErrLogService capOvdErrLogService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toListPage", "加载CapOvdErrLog列表页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("capital/capOvdErrLog/capOvdErrLogList");
		return mav;
	}
	
	/**
	 * 到新增页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toAddPage", "加载CapOvdErrLog Add页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("capital/capOvdErrLog/capOvdErrLogModify");
		//this.prepare(request,mav);
		return mav;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toModifyPage", "加载CapOvdErrLog Modify页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("capital/capOvdErrLog/capOvdErrLogModify");
		//this.prepare(request,mav);
		
		String id=request.getParameter("id");
		CapOvdErrLogVO capOvdErrLogVO = this.capOvdErrLogService.selectById(Long.valueOf(id));
        mav.addObject("capOvdErrLogVO", capOvdErrLogVO);
		return mav;
	}
	
	//加载数据字典数据、传值等 ？
    public void prepare(HttpServletRequest request,ModelAndView mav){
    	
    }

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initCapOvdErrLogList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		CapOvdErrLogQueryCondition qc = new CapOvdErrLogQueryCondition();
		
		String paySchNo = request.getParameter("paySchNo");//支付表号
		String cstNm = request.getParameter("cstNm");//客户名称
		String mdfTm = request.getParameter("mdfTm");//更新日期
		String errorCode = request.getParameter("errorCode");//异常原因
		if (StringUtils.isNotEmpty(paySchNo)) {
			qc.setPaySchNo(paySchNo.trim());
		}
		if (StringUtils.isNotEmpty(cstNm)) {
			qc.setCstNm(cstNm.trim());
		}
		if (StringUtils.isNotEmpty(mdfTm)) {
			qc.setMdfTm(mdfTm);
		}
		if (StringUtils.isNotEmpty(errorCode)) {
			qc.setErrorCode(errorCode);
		}
		page.setCondition(qc);
		BaseLogUtils.info(logger, "initCapOvdErrLogList", "初始化CapOvdErrLog列表页面数据.DATA:"+JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		Pager pager = this.capOvdErrLogService.searchListPage(page);
		List<CapOvdErrLogVO> list = (List<CapOvdErrLogVO>) pager.getResultList();
		ListPageVO<CapOvdErrLogVO> listPage = new ListPageVO<CapOvdErrLogVO>(list, pager.getTotalCount());
		return listPage;
	}
    /**
     * 更新页面弹出框
     */
    @RequestMapping(value = "/updateData.do", method = { RequestMethod.GET})
    @ResponseBody
    public ModelAndView updateData(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "updateData", "加载罚息编辑页面.",CurrentThreadContext.getCurrentUserName());
        String id=request.getParameter("id");
        //String ovdPenaltyAmt=request.getParameter("ovdPenaltyAmt");
        String marks=request.getParameter("marks");
        String paySchId=request.getParameter("paySchId");
        BaseLogUtils.info(logger, "updateData", "支付表ID:"+paySchId);
        //调用罚息计算接口
        long ovdPenaltyAmt =this.capOvdErrLogService.calculatePenaltyAmt(marks, Long.parseLong(id), Long.parseLong(paySchId))  ;
        ModelAndView mav = new ModelAndView("capital/capOvdErrLog/handleData");
        mav.addObject("ovdPenaltyAmt", ovdPenaltyAmt);
        mav.addObject("mark", marks);
        mav.addObject("id", id);
        mav.addObject("paySchId", paySchId);
        return mav;
    }
    /**
     * 忽略数据
     */
    @RequestMapping(value = "/ignoreData.do", method = { RequestMethod.POST})
    @ResponseBody
    public DataResultVO ignoreData(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "ignoreData", "加载罚息编辑页面.",CurrentThreadContext.getCurrentUserName());
        String id=request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "忽略成功");
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "ignoreData", "忽略CapOvdErrLog数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }
        try {
            boolean success = this.capOvdErrLogService.ignoreData(Long.parseLong(id));
            if(!success){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("忽略失败");
                BaseLogUtils.info(logger, "ignoreData", "忽略CapOvdErrLog数据失败,ID:"+id, CurrentThreadContext.getCurrentUserName());
            }
            BaseLogUtils.info(logger, "removeCapOvdErrLogByIds", "忽略CapOvdErrLog数据成功,ID:"+id, CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "removeCapOvdErrLogByIds", "忽略CapOvdErrLog数据失败,ID:"+id+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "removeCapOvdErrLogByIds", "忽略CapOvdErrLog数据失败,系统错误.ID:"+id+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;

    }


	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeCapOvdErrLogByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(ids)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "removeCapOvdErrLogByIds", "删除CapOvdErrLog数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        List<Long> idsList = new ArrayList<Long>();
        JSONArray idsArray = JSONArray.fromObject(ids);
        for (Object object : idsArray) {
            idsList.add(Long.valueOf(object.toString()));
        }
		
		try {
			boolean success = this.capOvdErrLogService.removeByIds(idsList);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
				BaseLogUtils.info(logger, "removeCapOvdErrLogByIds", "删除CapOvdErrLog数据失败,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "removeCapOvdErrLogByIds", "删除CapOvdErrLog数据成功,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "removeCapOvdErrLogByIds", "删除CapOvdErrLog数据失败,ID:"+idsList.toString()+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeCapOvdErrLogByIds", "删除CapOvdErrLog数据失败,系统错误.ID:"+idsList.toString()+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getCapOvdErrLogById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "getCapOvdErrLogById", "获取CapOvdErrLog数据,主键参数为空.", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			CapOvdErrLogVO vo = this.capOvdErrLogService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getCapOvdErrLogById", "获取CapOvdErrLog数据不存在,ID:"+id, CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getCapOvdErrLogById", "获取CapOvdErrLog数据成功,ID:"+id, CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "getCapOvdErrLogById", "获取CapOvdErrLog数据失败,ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getCapOvdErrLogById", "获取CapOvdErrLog数据失败,系统错误.ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object addCapOvdErrLog(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		CapOvdErrLogVO entity = null;//获取参数
		try {
			entity = this.getRequestParamForCapOvdErrLog(request);//获取参数
			Long id = this.capOvdErrLogService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "addCapOvdErrLog", "新增CapOvdErrLog数据成功,ID:"+id+".DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.info(logger, "addCapOvdErrLog", "新增CapOvdErrLog数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.error(logger, "addCapOvdErrLog", "新增CapOvdErrLog数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modifyCapOvdErrLog(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,SysLogConstant.LOG_CMM_UPDATE_SUCC);
		CapOvdErrLogVO entity = null;
		try {
			entity = this.getRequestParamForCapOvdErrLog(request);
			if(entity.getId()==null){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
				BaseLogUtils.info(logger, "modifyCapOvdErrLog", "修改CapOvdErrLog信息,主键参数为空！.", CurrentThreadContext.getCurrentUserName());
				return result;
			}

			boolean success = this.capOvdErrLogService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
				BaseLogUtils.info(logger, "modifyCapOvdErrLog", "修改CapOvdErrLog数据失败.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
				return result;
			}
			BaseLogUtils.info(logger, "modifyCapOvdErrLog", "修改CapOvdErrLog数据成功.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.info(logger, "modifyCapOvdErrLog", "修改CapOvdErrLog数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.error(logger, "modifyCapOvdErrLog", "修改CapOvdErrLog数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 更新业务处理
	 * @param request
	 * @return
	 * @throws BaseException
	 */
	@RequestMapping(value = "/updateBusiProcessing.do", method = { RequestMethod.POST})
	@ResponseBody
	public Object updateBusiProcessing(HttpServletRequest request) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		// 主键ID
		String id = request.getParameter("id");
		// 支付表ID
		String paySchId = request.getParameter("paySchId");
		// 更新后的罚息金额
		String penaltyAmt = request.getParameter("penaltyAmt");

		CapOvdErrLogDTO dto = new CapOvdErrLogDTO();
		try {
			dto.setId(Long.parseLong(id));
			dto.setPaySchId(Long.parseLong(paySchId));
			dto.setPenaltyAmt(DecimalUtils.convertYuanToFen(Double.parseDouble(penaltyAmt)));

			boolean bol = capOvdErrLogService.updateBusiProcessing(dto);
			if (!bol) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
			}
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
			BaseLogUtils.info(logger, "updateBusiProcessing", "更新业务处理失败.DATA:" + JSONObject.toJSONString(dto) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
			BaseLogUtils.error(logger, "updateBusiProcessing", "更新业务处理失败,系统错误.DATA:" + JSONObject.toJSONString(dto) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 获取请求参数
	 * @param request 请求
	 * @return 
	 */
	private CapOvdErrLogVO getRequestParamForCapOvdErrLog(HttpServletRequest request) throws BaseException{
		//获取参数
		String id = request.getParameter("id");//主键
		String insId = request.getParameter("insId");//资管机构ID
		String paySchId = request.getParameter("paySchId");//支付表ID
		String paySchNo = request.getParameter("paySchNo");//支付表号
		String cstId = request.getParameter("cstId");//客户ID
		String cstNm = request.getParameter("cstNm");//客户名称
		String ovdDt = request.getParameter("ovdDt");//最早逾期日期
		String ovdRentAmt = request.getParameter("ovdRentAmt");//逾期租金(分)
		//String restIntrAmt = request.getParameter("restIntrAmt");//欠息(分)
		String restIntrDt = request.getParameter("restIntrDt");//罚息日期
		String dataStsCd = request.getParameter("dataStsCd");//数据状态:0.待处理 1.处理中 2.已处理

		//验证参数并赋值
		CapOvdErrLogVO entity = new CapOvdErrLogVO();
 		//entity.setInsId(insId);//资管机构ID
 		//entity.setPaySchId(paySchId);//支付表ID
 		//entity.setPaySchNo(paySchNo);//支付表号
 		//entity.setCstId(cstId);//客户ID
 		//entity.setCstNm(cstNm);//客户名称
 		//entity.setOvdDt(ovdDt);//最早逾期日期
 		//entity.setOvdRentAmt(ovdRentAmt);//逾期租金(分)
 		//entity.setRestIntrAmt(restIntrAmt);//欠息(分)
 		//entity.setRestIntrDt(restIntrDt);//罚息日期
 		//entity.setDataStsCd(dataStsCd);//数据状态:0.待处理 1.处理中 2.已处理
	
//		if (StringUtils.isBlank(name)) {
//            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "名称不能为空.");
//      }
//      if (StringUtils.isNotBlank(num)) {
//          if (!StringUtils.isUnsignedNumeric(num)) {
//                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请填写正确的数字.");
//          }
//      }

		Date tm=new Date();
		if (StringUtils.isNotBlank(id)) {
			entity.setId(Long.valueOf(id));
			entity.setMdfTm(tm);
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
		}else{
			entity.setCrtTm(tm);
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			//entity.setCrtUsrOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前用户组织机构代码
            //entity.setOrgCd(CurrentThreadContext.getCurrentBuOrgCd());//事业部组织机构代码
		}
		
		return entity;
	}
}

